import sys
from pathlib import Path
import json
from typing import Optional

sys.path.append(str(Path(__file__).parent.parent.parent))
from reqapi.api import BaseApi, ApiConfig
from model.sms_up_login_models import SmsUpSignInRequest, SmsUpSignInResponse


class AuthSmsUpLoginApi(BaseApi):
    """短信上行登录API"""
    
    def sms_up_sign_in(self, mobile: str, code: str = "", area: str = "86", raise_on_error: bool = False) -> Optional[SmsUpSignInResponse]:
        """短信上行登录，统一风格，异常和错误码返回 None"""
        endpoint = "/api/user/Auth/SmsUpSignIn"
        url = f"{self.BASE_URL}{endpoint}"
        request = SmsUpSignInRequest(
            Area=area,
            Code=code,
            DeviceName=f"{ApiConfig.BRAND} {ApiConfig.DEVICE_TYPE}",
            Mobile=mobile,
            Sessionid=self.device_id or ""
        )
        request_data = {
            "Area": request.Area,
            "Code": request.Code,
            "DeviceName": request.DeviceName,
            "Mobile": request.Mobile,
            "Sessionid": request.Sessionid
        }
        headers = self.common_headers.copy()
        headers["apptype"] = "7"
        headers["authorization"] = "Bearer"
        print("\n=== 请求信息 ===")
        print(f"请求URL: {url}")
        print(f"请求方法: POST")
        print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
        print(f"请求数据: {json.dumps(request_data, indent=2, ensure_ascii=False)}")
        try:
            response = self.interceptor.send_request(url, json=request_data, headers=headers, need_encrypt=False)
            print("\n=== 响应信息 ===")
            if isinstance(response, dict):
                resp_json = response
            elif hasattr(response, 'json'):
                resp_json = response.json()
            else:
                resp_json = response
            print(f"响应内容: {json.dumps(resp_json, indent=2, ensure_ascii=False)}")
            code_val = resp_json.get('Code', resp_json.get('code', -1))
            if code_val != 0:
                print(f"API返回错误: {resp_json.get('Msg', resp_json.get('msg', '未知错误'))}")
                if raise_on_error:
                    raise Exception(f"业务处理失败: {resp_json.get('Msg', resp_json.get('msg'))}")
                return None
            if hasattr(SmsUpSignInResponse, 'from_dict'):
                return SmsUpSignInResponse.from_dict(resp_json)
            return SmsUpSignInResponse(**resp_json)
        except Exception as e:
            print(f"请求发生错误: {str(e)}")
            if raise_on_error:
                raise
            return None


def main():
    """测试短信上行登录API"""
    try:
        # 使用示例设备ID
        device_id = "Z+Y6b2IPUIgDAPCT+TR/1bNK"
        
        # 创建API实例
        api = AuthSmsUpLoginApi(
            device_token=device_id,
            device_id=device_id,
            auth_token="Bearer",  # 根据请求示例设置
            uk="5FGalKSuELr9iaAi6w13dX3GZq3J7fXtzyv3SloVrBx5pKxpaC82CMwdxSIZMo11L"  # 示例UK值
        )
        
        # 发送请求 - 使用示例手机号和验证码
        response = api.sms_up_sign_in(
            mobile="15999957262",  # 示例手机号，实际使用时替换
            code="",  # 示例验证码，实际使用时替换为收到的验证码
            area="86"  # 区号，默认中国
        )
        
        print("\n短信上行登录结果:")
        if response is None:
            print("短信上行登录失败，可能是登录信息失效或接口返回错误。")
            return None
        print(f"状态码: {getattr(response, 'Code', None)}")
        print(f"消息: {getattr(response, 'Msg', None)}")
        print(f"提示类型: {getattr(response, 'TipType', None)}")
        data = getattr(response, 'Data', None)
        if isinstance(data, dict):
            token = data.get('Token')
            nickname = data.get('NickName')
            is_open_stock = data.get('IsOpenStock')
            is_reg = data.get('IsReg')
            tips = data.get('ForeignAccountTips')
            sms_up_content = data.get('SmsUpContent')
            sms_up_number = data.get('SmsUpNumber')
        else:
            token = getattr(data, 'Token', None)
            nickname = getattr(data, 'NickName', None)
            is_open_stock = getattr(data, 'IsOpenStock', None)
            is_reg = getattr(data, 'IsReg', None)
            tips = getattr(data, 'ForeignAccountTips', None)
            sms_up_content = getattr(data, 'SmsUpContent', None)
            sms_up_number = getattr(data, 'SmsUpNumber', None)
        if getattr(response, 'Code', -1) == 0 and data:
            if token:
                print(f"登录令牌: {token}")
            if nickname:
                print(f"用户昵称: {nickname}")
            if is_open_stock is not None:
                print(f"是否开通库存: {is_open_stock}")
            if is_reg is not None:
                print(f"是否注册: {is_reg}")
            if tips:
                print(f"外部账号提示: {tips}")
            if sms_up_content:
                print(f"短信上行内容: {sms_up_content}")
            if sms_up_number:
                print(f"短信上行号码: {sms_up_number}")
            return token
        else:
            print(f"登录失败，错误码: {getattr(response, 'Code', None)}")
            print(f"错误信息: {getattr(response, 'Msg', None)}")
            return None
        
    except Exception as e:
        print(f"短信上行登录失败: {e}")
        return None


if __name__ == "__main__":
    main()
